<template>
    <div class="personnel-view">
        <el-row class="toolbar" :gutter="16" style="margin-bottom:12px;">
            <el-col :span="18">
                <el-input v-model="searchForm.name" placeholder="姓名" style="width:200px;margin-right:8px;" clearable />
                <el-input v-model="searchForm.phone" placeholder="手机号" style="width:200px;margin-right:8px;"
                    clearable />
                <el-select v-model="searchForm.department" placeholder="部门" style="width:200px;margin-right:8px;"
                    clearable>
                    <el-option v-for="d in departments" :key="d" :label="d" :value="d" />
                </el-select>
                <el-button type="primary" @click="fetchPersonnels">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-col>
            <el-col :span="6" style="text-align:right;">
                <el-button type="primary" @click="onAdd">新增</el-button>
                <el-button type="danger" @click="handleBatchDelete"
                    :disabled="multipleSelection.length === 0">删除</el-button>
            </el-col>
        </el-row>

        <el-table :data="personnels" v-loading="loading" @selection-change="handleSelectionChange" style="width:100%">
            <el-table-column type="selection" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="gender" label="性别" />
            <el-table-column prop="deptName" label="部门" />
            <el-table-column prop="positionName" label="职位" />
            <el-table-column prop="phoneNumber" label="手机号" />
            <el-table-column prop="school" label="院校" />
            <el-table-column prop="major" label="专业" />
            <el-table-column prop="homeAddress" label="家庭住址" />
            <el-table-column label="在职(天)">
                <template #default="{ row }">
                    <span>{{ ageDays(row.createdAt) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="类别" />
            <el-table-column prop="createdAt" label="创建时间">
                <template #default="{ row }">
                    <span>{{ formatDate(row.createdAt) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
                <template #default="{ row }">
                    <el-button type="text" size="small" @click="onView(row)">查看</el-button>
                    <el-button type="text" size="small" @click="onEdit(row)">编辑</el-button>
                    <el-button type="text" size="small" style="color:#f56c6c" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
            :current-page.sync="page" @size-change="onPageSizeChange" @current-change="onPageChange"
            style="margin-top:12px;text-align:right;" />

        <!-- 新增/编辑/查看对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
            <el-form :model="form" ref="formRef" label-width="100px">
                <el-form-item label="姓名">
                    <el-input v-model="form.name" :disabled="isView" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="form.gender" placeholder="请选择" :disabled="isView">
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门">
                    <el-input v-model="form.deptName" :disabled="isView" />
                </el-form-item>
                <el-form-item label="职位">
                    <el-input v-model="form.positionName" :disabled="isView" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="form.phoneNumber" :disabled="isView" />
                </el-form-item>
                <el-form-item label="院校">
                    <el-input v-model="form.school" :disabled="isView" />
                </el-form-item>
                <el-form-item label="专业">
                    <el-input v-model="form.major" :disabled="isView" />
                </el-form-item>
                <el-form-item label="家庭住址">
                    <el-input v-model="form.homeAddress" :disabled="isView" />
                </el-form-item>
                <el-form-item label="类别">
                    <el-input v-model="form.categoryName" :disabled="isView" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm" v-if="!isView">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const API_BASE = 'http://localhost:5149/api/Personnels/PersonnelShow'

const loading = ref(false)
const personnels = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const multipleSelection = ref([])

const searchForm = reactive({ name: '', phone: '', department: null })

const departments = ref([])
const dialogVisible = ref(false)
const isEditing = ref(false)
const isView = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = reactive({ id: null, name: '', gender: '', deptName: '', positionName: '', phoneNumber: '', school: '', major: '', homeAddress: '', categoryName: '', createdAt: null })

function handleSelectionChange(val) { multipleSelection.value = val }

function formatDate(value) {
    if (!value) return ''
    const d = new Date(value)
    return d.toLocaleString()
}

function calcDays(createdAt) {
    if (!createdAt) return '-'
    const created = new Date(createdAt)
    const now = new Date()
    const diff = now.getTime() - created.getTime()
    return Math.floor(diff / (1000 * 60 * 60 * 24))
}

function ageDays(createdAt) {
    // 与 calcDays 功能一致，但始终返回数字（便于表格展示）
    const v = calcDays(createdAt)
    return v === '-' ? '-' : v
}

async function fetchPersonnels() {
    loading.value = true
    try {
        // 后端分页查询参数使用大写字段名（Page, PageSize, Name, DepartmentId 等）
        const params = { Page: page.value, PageSize: pageSize.value, Name: searchForm.name, Phone: searchForm.phone }
        // 如果前端传递了部门/职位/类别的 id，则以后端期望的参数名传递
        if (searchForm.department) params.DepartmentId = searchForm.department
        if (searchForm.positionId) params.PositionId = searchForm.positionId
        if (searchForm.categoryId) params.CategoryId = searchForm.categoryId
        const res = await axios.get(API_BASE, { params })
        const payload = res.data ?? res
        console.debug('fetchPersonnels response:', res)
        // 规范化返回为数组，兼容多种后端返回结构
        let listRaw = payload?.data?.items ?? payload?.data ?? payload?.items ?? payload
        if (!Array.isArray(listRaw)) {
            if (listRaw && typeof listRaw === 'object' && Array.isArray(listRaw.items)) {
                listRaw = listRaw.items
            } else if (Array.isArray(payload)) {
                listRaw = payload
            } else {
                // 尝试从 payload 中找到第一个数组字段
                const arr = payload && typeof payload === 'object' ? Object.values(payload).find(v => Array.isArray(v)) : null
                listRaw = Array.isArray(arr) ? arr : []
                // 如果仍为空，判断 payload 是否像单条记录（可能后端直接返回对象而非数组）
                if (!listRaw.length && payload && typeof payload === 'object') {
                    const sampleKeys = ['id', 'name', 'createdAt', 'deptName', 'phoneNumber']
                    const looksLikeRecord = sampleKeys.some(k => Object.prototype.hasOwnProperty.call(payload, k))
                    if (looksLikeRecord) listRaw = [payload]
                }
            }
        }
        const list = listRaw
        console.debug('normalized list (length):', Array.isArray(list) ? list.length : 0, list)
        personnels.value = (list || []).map(x => ({
            id: x.id ?? x.Id,
            name: x.name ?? x.Name,
            gender: x.gender ?? x.Gender,
            deptName: x.deptName ?? x.DeptName ?? x.department_DeptName ?? x.Department_DeptName ?? '',
            positionName: x.positionName ?? x.PositionName ?? x.position_PositionName ?? x.Position_PositionName ?? '',
            phoneNumber: x.phoneNumber ?? x.PhoneNumber ?? x.phone ?? x.Phone ?? '',
            school: x.school ?? x.School ?? '',
            major: x.major ?? x.Major ?? '',
            homeAddress: x.homeAddress ?? x.HomeAddress ?? '',
            createdAt: x.createdAt ?? x.CreatedAt ?? x.personCreatedAt ?? x.PersonCreatedAt ?? x.CreateTime ?? x.create_time ?? null,
            categoryName: x.categoryName ?? x.CategoryName ?? x.category_CategoryName ?? x.Category_CategoryName ?? '',
        }))
        total.value = payload.data?.total || payload.total || personnels.value.length

        // 构建部门下拉
        departments.value = Array.from(new Set(personnels.value.map(p => p.deptName).filter(Boolean)))
    } catch (err) {
        console.error('fetchPersonnels error', err)
    } finally {
        loading.value = false
    }
}

function resetSearch() { searchForm.name = ''; searchForm.phone = ''; searchForm.department = null }

function onAdd() {
    isEditing.value = false
    isView.value = false
    dialogTitle.value = '新增员工'
    Object.assign(form, { id: null, name: '', gender: '', deptName: '', positionName: '', phoneNumber: '', school: '', major: '', homeAddress: '', categoryName: '', createdAt: null })
    dialogVisible.value = true
}

function onView(row) {
    isEditing.value = false
    isView.value = true
    dialogTitle.value = '查看员工'
    Object.assign(form, row)
    dialogVisible.value = true
}

function onEdit(row) {
    isEditing.value = true
    isView.value = false
    dialogTitle.value = '编辑员工'
    Object.assign(form, row)
    dialogVisible.value = true
}

async function handleDelete(row) {
    try {
        await axios.delete(`${API_BASE}/${row.id}`)
        fetchPersonnels()
    } catch (err) { console.error('delete error', err) }
}

async function submitForm() {
    try {
        if (isEditing.value && form.id) {
            await axios.put(`${API_BASE}/${form.id}`, form)
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchPersonnels()
            return
        }

        // 新增
        await axios.post(API_BASE, form)
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchPersonnels()
    } catch (err) {
        console.error('submit error', err)
        ElMessage.error('保存失败')
    }
}

async function handleBatchDelete() {
    if (!multipleSelection.value.length) return
    const ids = multipleSelection.value.map(r => r.id)
    try {
        await axios.delete(API_BASE, { data: { ids } })
        fetchPersonnels()
    } catch (err) { console.error('batch delete error', err) }
}

function onPageSizeChange(size) { pageSize.value = size; fetchPersonnels() }
function onPageChange(p) { page.value = p; fetchPersonnels() }

onMounted(() => { fetchPersonnels() })
</script>

<style scoped>
.toolbar {
    margin-bottom: 12px
}

.personnel-view .el-table .cell {
    white-space: nowrap
}
</style>
